package com.liu.nb.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.liu.nb.entity.SysUser;
import com.liu.nb.service.ISysMenuService;
import com.liu.nb.util.Const;
import com.liu.nb.util.RedisUtil;
import com.liu.nb.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.security.Principal;

/*
* 这个类是获得验证码的
* */
@RestController
public class AuthorizeController extends BaseController{
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private ISysMenuService sysMenuService;
//    lineCaptcha是获得验证码的，每一次都不一样，所以直接new不注册成bean
    private LineCaptcha lineCaptcha;
    @RequestMapping("/captcha")
//    获取验证码
    public Result getCaptcha(){
        lineCaptcha = new LineCaptcha(90, 40);
        String key = UUID.randomUUID().toString();
        String base64Img=lineCaptcha.getImageBase64Data();
        String captchaVal=lineCaptcha.getCode();
//        hset()的第一个参数是map的名字，第二个是map中的键的名字，第三个是键对应的值
        super.redisUtil.hset(Const.CAPTCHA_KEY,key,captchaVal,120);
        return Result.success(MapUtil.builder()
                .put("token",key)
                .put("captchaImg",base64Img)
                .build()
        );
    }
    //判断用户的角色只有admin才可以访问
    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/test")
    public Result test(){
        return  Result.success(sysMenuService.list());
    }
    //判断用户的权限只有拥有“ sys:menu:delete ”权限的才可以访问
    @PreAuthorize("hasAnyAuthority('sys:menu:delete')")
    @RequestMapping("/test/password")
    public Result password(){
        String password=bCryptPasswordEncoder.encode("111111");
        boolean matches = bCryptPasswordEncoder.matches("111111", password);
        System.out.println(matches);
        return Result.success(password);
    }
//    获取用户导航栏信息
    @RequestMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        return Result.success(MapUtil.builder()
        .put("id",sysUser.getId())
        .put("imgSrc",sysUser.getAvatar())
        .put("username",sysUser.getUsername())
        .put("created",sysUser.getCreated())
        .map());
    }
}
